﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ICMS.PluginInterfaces;
using SharpCompress.Reader;
using SharpCompress.Common;
using SharpCompress.Archive;
using commonImportPlugin.Factorys;
using commonImportPlugin.FilesCore;
using commonImportPlugin.Common;
using commonImportPlugin.Config;
using commonImportPlugin.FilesCore.MedicalFile;
using commonImportPlugin.Configs.Other;
using commonImportPlugin.Configs.MedicalFile;

namespace commonImportPlugin.Core.Match
{
    /// <summary>
    /// 《普通模式通用数据匹配类》
    /// 该模式主要是通用List<ICData>和List<MedicalData>
    /// 数据间任意二者根据银行卡号，身份证，来匹配
    /// /// </summary>
    public class matchCoreGeneral : MatchCore
    {
        CommonUtil common = CommonUtil.GetInstance();
        MatchBase matchBase = new MatchBase();
        static MatchConfig config =null;
        static Context context;
        public matchCoreGeneral GetInstance()
        {
            if (IsGetConfigSucceed())
            {
                context = Context.GetConfig();
                return new matchCoreGeneral();
            }
            return null;
        }
        private bool IsGetConfigSucceed()
        {
            config = MatchConfig.GetConfig();
            if (config == null)
                return false;
            else
                return true;
        }
        /// <summary>
        /// 一种格式间的匹配
        /// </summary>
        /// <typeparam name="T">类型1</typeparam>
        /// <typeparam name="C">类型2（参数）</typeparam>
        /// <param name="match1">数据1</param>
        /// <param name="match2">数据2</param>
        /// <param name="_config">参数</param>
        /// <param name="orderId"></param>
        /// <param name="errorIsContinue"></param>
        /// <param name="paramList"></param>
        /// <returns></returns>
        protected override List<T> OneFormatMatch<T,C>(List<T> match1, List<T> match2,C _config,string orderId, params object[] paramList)
        {
            Type type = typeof(T);
            if (type.Name != "ICData")
                throw new Exception("执行matchCoreGeneral.oneFormatMatch函数时参数设置有误！");
            ///////////获取数据///////
            List<ICData> match1Datas = (List<ICData>)(Object)match1;//数据1
            List<ICData> match2Datas = (List<ICData>)(Object)match2;//数据2
            string configRules = (string)(Object)_config;//配置

            string[] configSplits = configRules.Split('^');//分割匹配参数
            string[] matchItems = configSplits[3].Split('|');//分割匹配项
            string errorMessage = configSplits[4];//匹配报错提示

            List<ICData> finalICDatas = null;
            ICData icData2 = null;

            List<string> matchFails = new List<string>();//匹配失败的数据           
            matchFails.Add("");//预留一位置

            ///////判断匹配项/////
            #region 判断匹配项
            bool isMatchBankCardId = matchItems.Contains("bankCardId") ? true : false;
            bool isMatchPersonId = matchItems.Contains("personId") ? true : false;
            #endregion

            #region 筛选
            //匹配筛选
            finalICDatas = match1Datas.FindAll(delegate(ICData icData1)
            {
                icData2 = match2Datas.Find(delegate(ICData IcData2)
                {
                    #region 匹配
                    //匹配银行卡号
                    if (isMatchBankCardId && icData1.BankCardID != IcData2.BankCardID)
                        return false;
                    //匹配身份证号
                    if (isMatchPersonId && icData1.PersonID != IcData2.PersonID)
                        return false;
                    return true;
                    #endregion
                });

                if (icData2 != null)
                {
                    matchBase.MergeICData(icData1, icData2);//合并数据
                    //剔除成功匹配的数据
                    match2Datas.Remove(icData2);
                }
                else
                {
                    string record = "";
                    record = isMatchBankCardId ? icData1.BankCardID : "";
                    record += isMatchPersonId ? "," + icData1.PersonID : "";
                    matchFails.Add(record.Trim(','));
                }
                return icData2 != null ? true : false;
            });
            #endregion

            matchBase.FailOperate(matchFails, errorMessage, orderId, config.notMatchIsContinue);

            return (List<T>)(Object)finalICDatas;           
        }

        /// <summary>
        /// 两种不同格式类型间的匹配
        /// </summary>
        /// <typeparam name="T1">类型1</typeparam>
        /// <typeparam name="T2">类型2</typeparam>
        /// <typeparam name="C">类型3（匹配参数）</typeparam>
        /// <param name="match1">数据1</param>
        /// <param name="match2">数据2</param>
        /// <param name="_config">匹配参数</param>
        /// <param name="orderId">工单号</param>
        /// <param name="errorIsContinue">失败是否继续</param>
        /// <param name="paramList">可变参数</param>
        /// <returns>结果</returns>
        protected override List<T1> TwoFormatMatch<T1, T2, C>(List<T1> match1, List<T2> match2, C _config, string orderId, params object[] paramList)
        {
            Type type1 = typeof(T1);
            Type type2 = typeof(T2);

            ////////检查参数是否正确////////
            if (type1.Name != "ICData" || type2.Name != "MedicalData")
            {
                throw new Exception("执行matchCoreLink.commonMatch函数时参数设置有误！");
            }

            string configRules = (string)(Object)_config;//配置

            string[] configSplits = configRules.Split('^');//分割匹配参数
            string[] matchItems = configSplits[3].Split('|');//分割匹配项
            string errorMessage = configSplits[4];//匹配报错提示

            List<ICData> match1Datas = (List<ICData>)(Object)match1;
            List<MedicalData> match2Datas = (List<MedicalData>)(Object)match2;

            List<ICData> finalICDatas = null;
            MedicalData Data2 = null;

            List<string> matchFails = new List<string>();//匹配失败的数据         
            matchFails.Add("");//预留一位置

            //判断匹配项
            bool isMatchBankCardId = matchItems.Contains("bankCardId") ? true : false;
            bool isMatchPersonId = matchItems.Contains("personId") ? true : false;

            #region 匹配筛选
            //匹配
            finalICDatas = match1Datas.FindAll(delegate(ICData Data1)
            {
                Data2 = match2Datas.Find(delegate(MedicalData _Data2)
                {
                    #region 匹配
                    //匹配银行卡号
                    if (isMatchBankCardId && Data1.BankCardID != _Data2.bankCardId)
                        return false;
                    //匹配身份证号
                    if (isMatchPersonId && Data1.PersonID != _Data2.personId)
                        return false;
                    return true;
                    #endregion
                });
                if (Data2 != null)
                {
                    #region 赋值
                    Data1.BankCardID = string.IsNullOrEmpty(Data1.BankCardID) ? Data2.bankCardId : Data1.BankCardID;//银行卡号
                    Data1.PersonID = string.IsNullOrEmpty(Data1.PersonID) ? Data2.personId : Data1.PersonID;//身份证号
                    Data1.SSData = string.Format("{0}{1}", Data1.SSData, Data2.Data);
                    //剔除匹配成功的
                    match2Datas.Remove(Data2);
                    #endregion
                }
                else
                {
                    string record = "";
                    record = isMatchBankCardId ? Data1.BankCardID : "";
                    record += isMatchPersonId ? "," + Data1.PersonID : "";
                    matchFails.Add(record.Trim(','));
                }
                return Data2 != null ? true : false;
            });
            #endregion

            matchBase.FailOperate(matchFails, errorMessage, orderId, config.notMatchIsContinue);

            return (List<T1>)(Object)finalICDatas;

        }

        /// <summary>
        /// 匹配函数接口
        /// </summary>
        /// <typeparam name="T1">可变参1</typeparam>
        /// <typeparam name="T2">可变参2</typeparam>
        /// <param name="match1">匹配的数据1(Dictionary<string,List<ICData>> 存放社保，金融，磁条）</param>
        /// <param name="match2">匹配的数据2（医保数据）</param>
        /// <param name="_config">匹配参数</param>
        /// <param name="orderId">工单号</param>
        /// <param name="errorIsContinue">错误是否继续</param>
        /// <returns>匹配结果,null表示失败</returns>
        public override List<ICData> CommonMatch<T1, T2>(T1 Data1, T2 Data2, string orderId, params object[] paramList)
        {
            try
            {
                Dictionary<string, List<ICData>> dictionarys = (Dictionary<string, List<ICData>>)(Object)Data1;//数据集1
                List<MedicalData> medicalDatas = (List<MedicalData>)(Object)Data2;//数据2
                string[] matchParameter
                    = config.matchParameters;

                List<ICData> finalIcDatas = new List<ICData>();//存放最终匹配结果的值

                if (matchParameter != null)
                {
                    #region 匹配项
                    for (int i = 0; i < matchParameter.Length; i++)
                    {
                        string[] parameters = matchParameter[i].Split('^');
                        string keyName = parameters[0].Trim();//匹配后存放的键值名称
                        string match1 = parameters[1].Trim();//第一项
                        string match2 = parameters[2].Trim();//第二项
                        string matchItems = parameters[3].Trim();//匹配项
                        string erroMessage = parameters[4].Trim();//错误提示
                        //社保匹配医保
                        if (match2 == "medical")
                        {
                            List<ICData> afterMatchSM = this.TwoFormatMatch<ICData, MedicalData, string>(dictionarys[match1], medicalDatas, matchParameter[i], orderId, config.notMatchIsContinue);
                            dictionarys.Add(keyName, afterMatchSM);
                        }//其他
                        else
                        {
                            List<ICData> afterMatch = this.OneFormatMatch<ICData, string>(dictionarys[match1], dictionarys[match2], matchParameter[i], orderId, config.notMatchIsContinue);
                            dictionarys.Add(keyName, afterMatch);
                        }
                        if (i == matchParameter.Length - 1)
                        {
                            finalIcDatas = dictionarys[keyName];
                        }
                    }
                    #endregion
                }
                return finalIcDatas;

            }
            catch (Exception e)
            {      
                throw new Exception("执行匹配函数函数出现错误！\nError Messages:"+e.Message);
            }
           
        }
    }
}
